#include "Player.h"
#include "WaveGen.h"
#include "KeyRead.h"

uint16_t FunctionKey[2];
uint16_t Keyboard[2];

typedef uint8_t (*KeyReadFun)(void);
KeyReadFun FunKeyTab[2];
KeyReadFun KeyTab[2];

uint8_t PitchCount[2];
uint8_t TimbreCount[2];
uint8_t DitherCount[2];
uint8_t VolumeCount[2];

void PlayerInit(void)
{
  uint8_t i;
  for(i = 0; i < 2; i++)
  { 
    FunctionKey[i] = 0;
    Keyboard[i] = 0;
    PitchCount[i] = PITCH_DEFAULT_VALUE;
    TimbreCount[i] = TIMBRE_DEFAULT_VALUE;
    DitherCount[i] = DITHER_DEFAULT_VALUE;
    VolumeCount[i] = VOLUME_DEFAULT_VALUE;
  }
  FunKeyTab[0] = GetFunKeyValueL;
  FunKeyTab[1] = GetFunKeyValueR;
  KeyTab[0] = GetKeyboardValueL;
  KeyTab[1] = GetKeyboardValueR;
}

void PlayerProcess(void)
{
  uint8_t i;
  for (i = 0; i < 2; i++)
  {
    FunctionKey[i] |= FunKeyTab[i]();
    Keyboard[i] |= KeyTab[i]();

    if (0 != (Keyboard[i] & 0xFF))
    {
      WaveGenPitchStart(i, (Keyboard[i] & 0xFF) - 1);
    }
    else
    {
      WaveGenPitchStop(i);
    }
    switch (FunctionKey[i]) // 抬手后处理
    {
    case KEY_PITCH_UP:
      if (PitchCount[i] < PITCH_MAX_NUM - 1)
      {
        PitchCount[i]++;
        WaveGenSetPitch(i, PitchCount[i]);
      }
      break;
    case KEY_PITCH_DOWN:
      if (PitchCount[i] > 0)
      {
        PitchCount[i]--;
        WaveGenSetPitch(i, PitchCount[i]);
      }
      break;
    case KEY_TIMBRE:
      TimbreCount[i]++;
      if (TimbreCount[i] == TIMBRE_MAX_NUM)
      {
        TimbreCount[i] = 0;
      }
      WaveGenSetTimbre(i, TimbreCount[i]);
      break;
    case KEY_DITHER:
      DitherCount[i]++;
      if (DitherCount[i] == DITHER_MAX_NUM)
      {
        DitherCount[i] = 0;
      }
      WaveGenSetDither(i, DitherCount[i]);
      break;
    case KEY_VOLUME_UP:
      if (VolumeCount[i] < VOLUME_MAX_NUM - 1)
      {
        VolumeCount[i]++;
        WaveGenSetAmplitude(i, VolumeCount[i]);
      }
      break;
    case KEY_VOLUME_DOWN:
      if (VolumeCount[i] > 0)
      {
        VolumeCount[i]--;
        WaveGenSetAmplitude(i, VolumeCount[i]);
      }
      break;
    case KEY_NONE:
    default:
      break;
    }

    FunctionKey[i] <<= 8;
    Keyboard[i] <<= 8;
  }
}
